#!/usr/bin/env python
# -*- coding: utf-8 -*-

from datetime import datetime
from persistent import Persistent
from persistent.list import PersistentList
import hashlib
import secrets

class User(Persistent):
    """用户模型"""
    
    def __init__(self, username, email=None):
        """初始化用户
        
        Args:
            username (str): 用户名
            email (str): 邮箱地址
        """
        super().__init__()
        self.username = username
        self.password_hash = None
        self.email = email
        self.is_active = True  # 用户状态：激活/禁用
        self.is_admin = False  # 是否为系统管理员
        self.created = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.last_login = None

        # 用户有权限的项目列表
        self.project_paths = PersistentList()
        
        # 用户角色列表（一个用户可以有多个角色）
        self.roles = PersistentList()
        
        # 用户组列表（一个用户可以属于多个用户组）
        self.groups = PersistentList()
        
        # 用户会话信息
        self.token = None
        self.token_expire = None
    
    def add_role(self, role_name):
        """为用户添加角色"""
        if role_name not in self.roles:
            self.roles.append(role_name)
            self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self._p_changed = True
    
    def remove_role(self, role_name):
        """移除用户角色"""
        if role_name in self.roles:
            self.roles.remove(role_name)
            self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self._p_changed = True
    
    def has_role(self, role_name):
        """检查用户是否具有指定角色"""
        return role_name in self.roles
    
    def update_last_login(self):
        """更新最后登录时间"""
        self.last_login = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self._p_changed = True
    
    def set_token(self, token, expire_time):
        """设置用户令牌"""
        self.token = token
        self.token_expire = expire_time
        self._p_changed = True
    
    def clear_token(self):
        """清除用户令牌"""
        self.token = None
        self.token_expire = None
        self._p_changed = True
    
    def set_password(self, password):
        """设置用户密码
        
        Args:
            password (str): 明文密码
        """
        # 生成盐值
        salt = secrets.token_hex(16)
        # 使用SHA-256哈希算法加密密码
        password_with_salt = password + salt
        self.password_hash = hashlib.sha256(password_with_salt.encode()).hexdigest() + ':' + salt
        self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self._p_changed = True
    
    def check_password(self, password):
        """验证密码
        
        Args:
            password (str): 明文密码
            
        Returns:
            bool: 密码是否正确
        """
        if not self.password_hash:
            return False
        
        try:
            # 分离哈希值和盐值
            hash_part, salt = self.password_hash.split(':')
            # 使用相同的盐值加密输入的密码
            password_with_salt = password + salt
            input_hash = hashlib.sha256(password_with_salt.encode()).hexdigest()
            return input_hash == hash_part
        except ValueError:
            return False
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'username': self.username,
            'email': self.email,
            'is_active': self.is_active,
            'is_admin': self.is_admin,
            'roles': list(self.roles),
            'created': self.created,
            'updated': self.updated,
            'last_login': self.last_login,
        }
